package com.csdj.t309.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService extends MessageListenerAdapter {
    private Logger log = LoggerFactory.getLogger("redisService");

    @Resource
    private RedisTemplate<String,Object> objectRedisTemplate;

    public void setString(String key,String value,int second){
        objectRedisTemplate.opsForValue().set(key,value,second,TimeUnit.SECONDS);
    }

    public String getString(String key){
        Object o = objectRedisTemplate.opsForValue().get(key);
        if(o==null)
            return null;


        return o.toString();
    }

    public void setObject(String key,Object obj){
        objectRedisTemplate.opsForValue().set(key,obj);
    }

    public <T> T getObject(String key){
        Object o = objectRedisTemplate.opsForValue().get(key);
        return (T)o;
    }

    public <T extends Object> T getObject(String key,Class clazz){
        Object o = objectRedisTemplate.opsForValue().get(key);
        if(o == null)return null;
        if(clazz.isInstance(o))
        if(o.getClass().getName().equalsIgnoreCase(clazz.getName())){
            return (T)o;
        }
        log.error("{}的值不是{}的实例",key,clazz.getName());
        return null;
    }

    /**
     * redis订阅消息处理
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
//        super.onMessage(message, pattern);
        log.info("channel:{} message:{}",new String(message.getChannel()),new String(message.getBody()));
    }
}
